﻿Imports ADOConnection

Public Class frmPhieuNXNoiBo

#Region "Paramaters"
    Public fViewPhieuNX As frmViewPhieuNX
    Public objPhieuXuat As CPhieuNX = Nothing
    Public objPhieuNhap As CPhieuNX = Nothing

    'Chi dung cho cmbLK(cmbLoaiMH) 
    'de kiem tra neu chon Loai Kho( Loai Thuoc) khac se mat du lieu mat hang
    Private objLKX As CDoiTuong
    Private objKhoX As CDoiTuong
    Private objLoaiMH As CLoaiThuoc

    'Cac bien dung de truy xuat du lieu in DatagridView
    Private sdaSLNX As IDbDataAdapter
    'Private bsSLNX As New BindingSource
    Private dsDataSet As DataSet
    'Private gridCTPhieu.RowCount As Integer = 0 'De xu ly SoKH khi them mathang moi 

    'Bien dung de tinh toan lai slton tai thoi diem cua phieu xuat can chinh sua
    Public sltonkh As Double = 0
    Public sltonth As Double = 0

    Private RowCount As Integer = 0 'De xu ly SoKH khi them mathang moi 

    Public Enum enumLabelNotify
        None = -1
        DOITUONG = 0
        MaColumn = 2
        HSDColumn = 3
        SLColumn = 4
    End Enum
#End Region

#Region "Events"

#Region "General"
    Private Sub frmPhieuNhap_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Lay danh sach Loai Kho
        Dim arys As ArrayList = Nothing
        Try

            lblTCX_ID.Text = CStr(BaseDB.ExecSql_DataValue("select kh from tblTCNX where L = 'X' and Ten = N'NB'"))
            txtTCX.Text = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATXUAT, lblTCX_ID.Text).Ten
            lblTCN_ID.Text = CStr(BaseDB.ExecSql_DataValue("select kh from tblTCNX where L = 'N' and Ten = N'NB'"))
            txtTCN.Text = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.TINHCHATNHAP, lblTCN_ID.Text).Ten

            arys = CDoiTuongs.GetDoiTuongList(enumDOITUONG.LOAIKHO)
            cmbLKX.DisplayMember = "Ten"
            cmbLKX.ValueMember = "KH"
            cmbLKX.DataSource = arys

            arys = CDoiTuongs.GetDoiTuongList(enumDOITUONG.LOAIKHO)
            cmbLKN.DisplayMember = "Ten"
            cmbLKN.ValueMember = "KH"
            cmbLKN.DataSource = arys

            'Lay danh sach Loai Thuoc 
            arys = CLoaiThuocs.GetLoaiThuocListByMaCha(CLoaiThuocs.GetLoaiThuocByTen("Kho 706").MaLoaiThuoc)
            cmbLoaiMH.DisplayMember = "TenLoaiThuoc"
            cmbLoaiMH.ValueMember = "MaLoaiThuoc"
            cmbLoaiMH.DataSource = arys 'Ko can de selectedindex = 0
            cmbLoaiMH.SelectedIndex = 4 'Mac dinh la THUOC

            If g_User.Ban_ID = enumPHANQUYEN.TCT Then
                btnXoa.Visible = False
                btnCapnhatNew.Visible = False
            Else
                Panel4.Height -= chkTCXacNhan.Height
                GroupBoxTGT.Dock = DockStyle.Fill
                chkTCXacNhan.Visible = False
            End If
            lblNotify.Text = ""
            Init()


        Catch ex As Exception
            ShowMessages(ex.ToString)
        End Try
    End Sub

    Private Sub cmbLKN_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLKN.SelectedIndexChanged
        lblLKN_ID.Text = CType(sender.SelectedItem, CDoiTuong).KH
    End Sub

    Private Sub cmbLKX_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLKX.Enter
        objLKX = CType(sender.SelectedItem, CDoiTuong)
    End Sub

    Private Sub cmbLK_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLKX.SelectedIndexChanged
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            'Kiem tra xem Loai Kho vua chon la Loai Kho khac hay ko va da co mat hang chua
            lblLKX_ID.Text = CType(sender.SelectedItem, CDoiTuong).KH
            If objLKX IsNot sender.SelectedItem Then
                If gridCTPhieu.RowCount > 0 Then
                    If MessageBox.Show("Chọn Loại kho khác sẽ mất các Mặt Hàng đang có.Bạn có chắc chọn không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) = Windows.Forms.DialogResult.Yes Then
                        dsDataSet.Tables(0).Clear()
                        gridCTPhieu.DataSource = dsDataSet.Tables(0).DefaultView
                    Else
                        'Quay tro lai truoc khi chon
                        cmbLKX.SelectedValue = objLKX.KH
                        lblLKX_ID.Text = objLKX.KH
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub cmbLoaiMH_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLoaiMH.Enter
        objLoaiMH = cmbLoaiMH.SelectedItem
    End Sub

    'Private Sub cmbLoaiMH_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLoaiMH.SelectedIndexChanged
    '    If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
    '        'Kiem tra xem Loai Thuoc vua chon la Loai Thuoc khac hay ko va da co mat hang chua
    '        If objLoaiMH IsNot sender.SelectedItem Then
    '            If gridCTPhieu.RowCount > 0 Then
    '                If MessageBox.Show("Chọn Loại Mặt Hàng khác sẽ mất các Mặt Hàng đang có.Bạn có chắc chọn không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) = Windows.Forms.DialogResult.Yes Then
    '                    dsDataSet.Tables(0).Clear()
    '                    gridCTPhieu.DataSource = dsDataSet.Tables(0).DefaultView
    '                Else
    '                    'Quay tro lai truoc khi chon
    '                    cmbLoaiMH.SelectedValue = objLoaiMH.MaLoaiThuoc
    '                End If
    '            End If
    '        End If
    '    End If
    'End Sub
#End Region

#Region "gridCTPhieu"
    Private Sub gridCTPhieu_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles gridCTPhieu.CellBeginEdit
        If e.ColumnIndex = gridCTPhieu.Columns("slkh").Index Then
            gridCTPhieu.Columns("slkh").DefaultCellStyle.Format = Nothing
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("slth").Index Then
            gridCTPhieu.Columns("slth").DefaultCellStyle.Format = Nothing
        End If
    End Sub

    Private Sub gridCTPhieu_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gridCTPhieu.Enter
        RowCount = GetRowCount()
        ShowSoKH_TGiaTri()
    End Sub

    Private Sub gridCTPhieu_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridCTPhieu.CellEnter
        lblNotify.Text = ""
        If (e.ColumnIndex = gridCTPhieu.Columns("slkh").Index And g_User.Ban_ID = enumPHANQUYEN.KEHOACH) Then
            If e.RowIndex = RowCount Or gridCTPhieu.Rows(e.RowIndex).Cells("sltonkh").Value Is DBNull.Value Then
                Exit Sub
            End If
            'Kiem tra ngay them moi co phai la ngay hien tai khong?
            'Neu la ngay hien tai thi lay sltonkh hien tai
            'Neu khong la ngay hien tai thi tinh sltonkh tai thoi diem do
            If dtNgay.Value.Date >= Date.Today Then
                If objPhieuXuat Is Nothing Then
                    Try
                        sltonkh = gridCTPhieu.Rows(e.RowIndex).Cells("sltonkh").Value
                    Catch ex As Exception
                        sltonkh = 0
                    End Try
                Else
                    CMatHangs.GetSLTonDenNgay(objPhieuXuat.DPNX_ID, gridCTPhieu.Rows(e.RowIndex).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                End If
            Else
                If objPhieuXuat Is Nothing Then
                    CMatHangs.GetSLTonDenNgay(-1, gridCTPhieu.Rows(e.RowIndex).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                Else
                    CMatHangs.GetSLTonDenNgay(objPhieuXuat.DPNX_ID, gridCTPhieu.Rows(e.RowIndex).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                End If
            End If
            If sltonkh > 0 Then
                lblNotify.Text = "Số lượng Tồn kế hoạch đến ngày " + dtNgay.Value.Date.ToString(FormatDateStyle()) + ": " + sltonkh.ToString(FormatQuantityStyle())
            Else
                lblNotify.Text = "Số lượng Tồn kế hoạch đến ngày " + dtNgay.Value.Date.ToString(FormatDateStyle()) + ": 0"
            End If
        End If
    End Sub

    Private Sub gridCTPhieu_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gridCTPhieu.KeyDown
        If e.KeyCode = Keys.Enter Then
            If gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("slth").Index And _
            g_User.Ban_ID = enumPHANQUYEN.TCT Then
                gridCTPhieu.SelectedCells(0).Value = gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("slkh").Value
            End If
            'Kiem tra mat hang da chon het slth hay chua
            'Neu roi thi check = true
            chkTCXacNhan.Checked = CheckTCXacNhan()
        ElseIf e.KeyCode = Keys.Delete Then
            If gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("slth").Index And _
            g_User.Ban_ID = enumPHANQUYEN.TCT Then
                gridCTPhieu.SelectedCells(0).Value = DBNull.Value
            ElseIf (gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("slkh").Index Or _
            gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("lo").Index Or _
            gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("hansd").Index Or _
            gridCTPhieu.SelectedCells(0).ColumnIndex = gridCTPhieu.Columns("gle").Index) And _
            g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                gridCTPhieu.SelectedCells(0).Value = DBNull.Value
                If gridCTPhieu.SelectedCells(0).ColumnIndex <> gridCTPhieu.Columns("hansd").Index Then
                    gridCTPhieu.Rows(gridCTPhieu.SelectedCells(0).RowIndex).Cells("thanhtien").Value = DBNull.Value
                    ShowSoKH_TGiaTri()
                End If
            End If
        End If

    End Sub

    'Thuc hien khi cap nhat slkh hay slth
    Private Sub gridCTPhieu_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridCTPhieu.CellEndEdit
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH _
        And (e.ColumnIndex = gridCTPhieu.Columns("slkh").Index _
            Or e.ColumnIndex = gridCTPhieu.Columns("slth").Index _
            Or e.ColumnIndex = gridCTPhieu.Columns("gle").Index _
            Or e.ColumnIndex = gridCTPhieu.Columns("thanhtien").Index) Then
            Dim slkh, gle As Double
            If gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value IsNot DBNull.Value Then
                If gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value < 0 Then
                    ShowMessages("Số lượng kế hoạch phải > 0")
                    gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value = DBNull.Value
                    Exit Sub
                End If
            End If

            Try
                slkh = gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value
            Catch ex As Exception
                slkh = 0
            End Try

            If slkh > sltonkh Then
                ShowMessages("Số lượng kế hoạch phải nhỏ hơn số lượng tồn kế hoạch.")
                gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value = 0
                Exit Sub
            End If

            Try
                gle = gridCTPhieu.Rows(e.RowIndex).Cells("gle").Value
            Catch ex As Exception
                gle = 0
            End Try

            '***Phai doi ra dung format truoc khi tinh thanh tien
            If slkh > 0 Then
                slkh = CType(slkh.ToString(FormatMoneyStyle()), Double)
            End If

            If gle > 0 Then
                gle = CType(gle.ToString(FormatMoneyStyle()), Double)
            End If

            'Tinh thanh tien sau khi format xong
            Dim thanhtien As Double = slkh * gle
            gridCTPhieu.Rows(e.RowIndex).Cells("thanhtien").Value = thanhtien
            ShowSoKH_TGiaTri()
        ElseIf g_User.Ban_ID = enumPHANQUYEN.TCT _
                    And e.ColumnIndex = gridCTPhieu.Columns("slth").Index Then
            Dim slkh, slth, gle As Double

            Try
                slth = gridCTPhieu.Rows(e.RowIndex).Cells("slth").Value
            Catch ex As Exception
                slth = 0
            End Try

            If slth > sltonth Then
                ShowMessages("Số lượng thực hiện phải nhỏ hơn số lượng tồn thực hiện.")
                gridCTPhieu.Rows(e.RowIndex).Cells("slth").Value = 0
                Exit Sub
            End If

            If slth > 0 And slth <> slkh Then
                gridCTPhieu.Rows(e.RowIndex).Cells("slkh").Value = slth
                slkh = slth
            End If

            Try
                gle = gridCTPhieu.Rows(e.RowIndex).Cells("gle").Value
            Catch ex As Exception
                gle = 0
            End Try

            '***Phai doi ra dung format truoc khi tinh thanh tien
            If slkh > 0 Then
                slkh = CType(slkh.ToString(FormatMoneyStyle()), Double)
            End If

            If gle > 0 Then
                gle = CType(gle.ToString(FormatMoneyStyle()), Double)
            End If

            'Tinh thanh tien sau khi format xong
            Dim thanhtien As Double = slkh * gle
            gridCTPhieu.Rows(e.RowIndex).Cells("thanhtien").Value = thanhtien
            ShowSoKH_TGiaTri()

            'Kiem tra mat hang da chon het slth hay chua
            'Neu roi thi check = true
            chkTCXacNhan.Checked = CheckTCXacNhan()
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("makhoden").Index Then
            If gridCTPhieu.Rows(e.RowIndex).Cells("makhoden").Value.ToString() = "0001" Then
                ShowMessages("Phải chọn Kho đến cụ thể.")
                'reset value
                gridCTPhieu.Rows(e.RowIndex).Cells("makhoden").Value = DBNull.Value
                'Focus Cell
                'For Each cell As DataGridViewCell In gridCTPhieu.SelectedCells
                '    cell.Selected = False
                'Next
                'gridCTPhieu.Rows(e.RowIndex).Cells("makhoden").Selected = True
                Exit Sub
            End If
        ElseIf e.ColumnIndex = gridCTPhieu.Columns("makho").Index Then
            If gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value.ToString() = "0001" Then
                ShowMessages("Phải chọn Kho đi cụ thể.")
                'reset value
                gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value = DBNull.Value
                ''Focus Cell
                'For Each cell As DataGridViewCell In gridCTPhieu.SelectedCells
                '    cell.Selected = False
                'Next
                'gridCTPhieu.Rows(e.RowIndex).Cells("makho").Selected = True
                Exit Sub
            End If

            If cmbLoaiMH.SelectedIndex < 0 Then
                ShowMessages("Phải chọn Loại Mặt Hàng trước mới có thể thêm mặt hàng")
                Exit Sub
            End If

            If cmbLKX.SelectedIndex < 0 Then
                ShowMessages("Phải chọn nhập vào Loại Kho trước mới có thể thêm mặt hàng")
                Exit Sub
            End If

            If gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value Is DBNull.Value Then
                ShowMessages("Phải chọn Kho chứa mặt hàng trước.")
                Exit Sub
            End If

            Dim frm As frmLoHang
            If objPhieuXuat IsNot Nothing Then
                frm = New frmLoHang(objPhieuXuat.DPNX_ID, objPhieuXuat.NGAY, cmbLKX.SelectedValue.ToString(), gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value.ToString())
            Else
                frm = New frmLoHang(cmbLKX.SelectedValue.ToString(), gridCTPhieu.Rows(e.RowIndex).Cells("makho").Value.ToString())
            End If

            frm.fCallPhieuNX = Me
            frm.ShowDialog(Me)
            RowCount = GetRowCount()
        End If
    End Sub

    Private Sub gridCTPhieu_UserDeletedRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles gridCTPhieu.UserDeletedRow
        RowCount = GetRowCount()
        ShowSoKH_TGiaTri()
    End Sub

    Private Sub gridCTPhieu_UserAddedRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles gridCTPhieu.UserAddedRow
        RowCount = GetRowCount()
        For count As Integer = 0 To RowCount - 1
            gridCTPhieu.Rows(count).HeaderCell.Value = (count + 1).ToString
        Next
        txtSoKH.Text = RowCount.ToString()
    End Sub
#End Region

#Region "Textbox"
    'To mau cho control khi Focus
    Private Sub textBox_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles txtSoPhieu.Enter, txtDVGN.Enter, dtNgay.Enter, txtTCX.Enter, txtTheoLenh.Enter, txtNguoiVP.Enter, txtSoKH.Enter, txtTrLuong.Enter, txtSoKien.Enter, txtTGiaTri.Enter, txtTCN.Enter
        Try
            If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                SetColorAllControls(sender, True)
                'If (CType(sender, TextBox) Is txtTCX) Or (CType(sender, TextBox) Is txtTCN) Then
                '    If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                '        lblNotify.Text = GetLabelNotify(enumLabelNotify.DOITUONG)
                '    End If
                'End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub textBox_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles txtDVGN.Leave, dtNgay.Leave, txtTCX.Leave, txtTheoLenh.Leave, txtNguoiVP.Leave, txtSoKH.Leave, txtTrLuong.Leave, txtSoKien.Leave, txtTGiaTri.Leave, txtTCN.Leave
        SetColorAllControls(sender, False)
        'lblNotify.Text = GetLabelNotify()
    End Sub

    Private Sub txtSoPhieu_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSoPhieu.KeyPress, txtTheoLenh.KeyPress, txtNguoiVP.KeyPress
        If sender Is txtSoPhieu Then
            e.KeyChar = Char.Parse(StrConv(e.KeyChar.ToString, VbStrConv.Uppercase))
        Else
            If CType(sender, TextBox).Text.Length = 0 Then
                e.KeyChar = Char.Parse(StrConv(e.KeyChar.ToString, VbStrConv.ProperCase))
            End If
        End If
    End Sub

    ''' <summary>
    ''' Update: 25-01-2010
    ''' Kiểm tra số phiếu có bị trùng không
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtSoPhieu_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSoPhieu.Leave
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            SetColorAllControls(sender, False)

            'Kiem tra phieu nay da ton tai chua
            Dim sophieu As String = txtSoPhieu.Text.Trim()
            'Chỉ cần một phiếu xuất is nothing là đủ
            If objPhieuXuat Is Nothing Then
                If (CPhieuNXs.IsExist(enumDOITUONG.TINHCHATNHAP, sophieu) Or CPhieuNXs.IsExist(enumDOITUONG.TINHCHATXUAT, sophieu)) Then
                    ShowMessages("Số phiếu này bị trùng.")
                    txtSoPhieu.Focus()
                End If
            Else
                If (CPhieuNXs.IsExist(enumDOITUONG.TINHCHATNHAP, sophieu, objPhieuNhap.DPNX_ID) Or CPhieuNXs.IsExist(enumDOITUONG.TINHCHATXUAT, sophieu, objPhieuXuat.DPNX_ID)) Then
                    ShowMessages("Số phiếu này bị trùng.")
                    txtSoPhieu.Focus()
                End If
            End If
        End If
    End Sub

    'Private Sub txtDoiTuong_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtTCX.DoubleClick, txtTCN.DoubleClick
    '    If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
    '        If sender Is txtTCX Then
    '            ShowFormDoiTuong(txtTCX, enumDOITUONG.TINHCHATXUAT)
    '        Else
    '            ShowFormDoiTuong(txtTCN, enumDOITUONG.TINHCHATNHAP)
    '        End If
    '    End If
    'End Sub

    'Private Sub txtDoiTuong_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTCX.KeyDown, txtTCN.KeyDown
    '    If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
    '        If e.KeyCode = Keys.F1 Then
    '            If sender Is txtTCX Then
    '                ShowFormDoiTuong(txtTCX, enumDOITUONG.TINHCHATXUAT)
    '            Else
    '                ShowFormDoiTuong(txtTCN, enumDOITUONG.TINHCHATNHAP)
    '            End If
    '        End If
    '    End If
    'End Sub

    'Private Sub txtDoiTuong_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtTCN.Leave, txtTCX.Leave
    '    Dim loai As enumDOITUONG
    '    If sender Is txtTCN Then
    '        loai = enumDOITUONG.TINHCHATNHAP
    '    ElseIf sender Is txtTCX Then
    '        loai = enumDOITUONG.TINHCHATXUAT
    '    End If
    '    Dim strTen As String = CType(sender, TextBox).Text
    '    If strTen <> "" Then
    '        Dim arrFind As ArrayList = CDoiTuongs.SearchDoiTuong(loai, strTen)
    '        If arrFind.Count = 0 Then
    '            ShowFormDoiTuong(sender, loai)
    '        ElseIf arrFind.Count > 1 Then
    '            Dim objDoiTuong As CDoiTuong = CType(arrFind(0), CDoiTuong)
    '            Select Case sender.Name
    '                Case txtTCX.Name
    '                    lblTCX_ID.Text = objDoiTuong.KH
    '                    txtTCX.Text = objDoiTuong.Ten
    '                Case txtTCN.Name
    '                    lblTCN_ID.Text = objDoiTuong.KH
    '                    txtTCN.Text = objDoiTuong.Ten
    '            End Select
    '        End If
    '    Else 'Neu textbox = "" thi xoa ID o label
    '        Select Case sender.Name
    '            Case txtTCX.Name
    '                lblTCX_ID.Text = ""
    '            Case txtTCN.Name
    '                lblTCN_ID.Text = ""
    '        End Select
    '    End If
    'End Sub
    Private Sub txtDoiTuong_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDVGN.DoubleClick
        If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
            ShowFormDoiTuong(enumDOITUONG.DONVI, txtDVGN.Text)
        End If
    End Sub

    Private Sub txtDoiTuong_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDVGN.KeyDown
        If e.KeyCode = Keys.F1 Then
            txtDoiTuong_DoubleClick(sender, Nothing)
        End If
    End Sub

    Private Sub txtDoiTuong_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDVGN.Leave
        SetColorAllControls(sender, False)
        'lblNotify.Text = GetLabelNotify()

        Dim loai As enumDOITUONG
        loai = enumDOITUONG.DONVI
        Dim strTen As String = CType(sender, TextBox).Text

        If strTen <> "" Then
            Dim arrFind As ArrayList = CDoiTuongs.SearchDoiTuong(loai, strTen)
            If arrFind.Count = 0 Then
                ShowFormDoiTuong(loai, strTen)
            ElseIf arrFind.Count = 1 Then
                Dim objDoiTuong As CDoiTuong = CType(arrFind(0), CDoiTuong)
                lblDVGN_ID.Text = objDoiTuong.KH
                txtDVGN.Text = objDoiTuong.Ten
            End If
        Else 'Neu strTen = "" thi xoa ID trong label
            lblDVGN_ID.Text = ""
        End If
    End Sub
#End Region

#Region "Button"
    Public Function CompareValue(ByVal value1 As Object, ByVal value2 As Object) As Boolean
        If value1 Is DBNull.Value And value2 Is DBNull.Value Then
            Return True
        ElseIf value1 IsNot DBNull.Value And value2 IsNot DBNull.Value Then
            If value1 = value2 Then
                Return True
            Else
                Return False
            End If
        End If
        Return False
    End Function

    Public Function InsertPhieuNXNoiBo() As Boolean
        'Thong tin Dau Phieu Xuat
        objPhieuXuat = New CPhieuNX()
        Dim objMH(RowCount - 1) As CMatHang

        If PopulatePhieuXuatInfo() Then
            For i As Integer = 0 To RowCount - 1
                If gridCTPhieu.Rows(i).Cells("makho").Value = "" Or gridCTPhieu.Rows(i).Cells("makho").Value = "0001" Then
                    ShowError("Kho đi chưa chọn")
                    gridCTPhieu.Rows(i).Cells("makho").Selected = True
                    Return False
                End If

                If gridCTPhieu.Rows(i).Cells("makhoden").Value = "" Or gridCTPhieu.Rows(i).Cells("makhoden").Value = "0001" Then
                    ShowError("Kho đến chưa chọn")
                    gridCTPhieu.Rows(i).Cells("makhoden").Selected = True
                    Return False
                End If
                objMH(i) = CMatHangs.GetMatHangByMa(gridCTPhieu.Rows(i).Cells("mathang_id").Value)
            Next

            'Kiem tra lai xem so luong luc bat dau ghi co > slton nua ko (truong hop dung nhieu may khi xuat phieu)
            Dim objMHang As CMatHang
            Dim drMH As DataGridViewRow
            Dim strErr As String
            For i As Integer = 0 To RowCount - 1
                drMH = gridCTPhieu.Rows(i)
                objMHang = CMatHangs.GetMatHangByMa(drMH.Cells("mathang_id").Value)
                CMatHangs.GetSLTonDenNgay(-1, objMHang.MatHang_ID, dtNgay.Value.Date, sltonkh, Nothing, Nothing, Nothing)
                If drMH.Cells("slkh").Value > sltonkh Then
                    strErr = "Số lượng kế hoạch của mặt hàng " + drMH.Cells("ten").Value.ToString() + " lớn hơn số lượng tồn kế hoạch"
                    drMH.Selected = True
                    Return False
                End If
            Next

            'Kiem tra va Them phieu nhap neu dc
            If objPhieuXuat.Insert() > 0 Then
                Dim i As Integer = 0
                For Each dr As DataRow In dsDataSet.Tables(0).Rows
                    dr("dpnx_id") = objPhieuXuat.DPNX_ID
                    objMH(i).MatHang_ID = gridCTPhieu.Rows(i).Cells("mathang_id").Value
                    objMH(i).SubstractSLTON(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value), ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slth").Value))
                    i += 1
                Next
                'Them lai cac SLNX vao tblSLNX
                Dim objSLNX As CSLNX
                For i = 0 To RowCount - 1
                    Dim dr As DataGridViewRow = gridCTPhieu.Rows(i)
                    objSLNX = New CSLNX()
                    objSLNX.DPNX_ID = objPhieuXuat.DPNX_ID
                    objSLNX.MATHANG_ID = dr.Cells("mathang_id").Value
                    objSLNX.SLKH = ChuanHoaSo(dr.Cells("slkh").Value)
                    objSLNX.SLTH = ChuanHoaSo(dr.Cells("slth").Value)
                    objSLNX.THANHTIEN = ChuanHoaSo(dr.Cells("thanhtien").Value)
                    Try
                        objSLNX.GhiChu = dr.Cells("ghichu").Value
                    Catch ex As Exception
                        objSLNX.GhiChu = Nothing
                    End Try
                    objSLNX.Insert()
                Next

                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.ThemMoi, objPhieuXuat)
            End If

            '***********************************************'
            ''    CHUYEN DOI THONG TIN THANH PHIEU NHAP    ''
            '***********************************************'
            'Thong tin Dau Phieu Nhap
            objPhieuNhap = New CPhieuNX(objPhieuXuat)
            objPhieuNhap.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP)
            If lblTCN_ID.Text = "" Then
                objPhieuNhap.TCNX = Nothing
            Else
                objPhieuNhap.TCNX = lblTCN_ID.Text
            End If
            objPhieuNhap.LK = lblLKN_ID.Text

            If objPhieuNhap.Insert() > 0 Then
                'Cap nhat lai nhung thay doi cua grid vao tblSLNX va tblTON
                For i As Integer = 0 To RowCount - 1
                    'Them cac mat hang moi vao
                    If objMH(i).Lo = "" Then
                        objMH(i).Lo = Nothing
                    End If
                    If objMH(i).HanSD = "" Then
                        objMH(i).HanSD = Nothing
                    End If
                    objMH(i).LK = CType(cmbLKN.SelectedItem, CDoiTuong).KH
                    objMH(i).Kho = gridCTPhieu.Rows(i).Cells("makhoden").Value
                    'Kiem tra mat hang nay da ton tai chua
                    If objMH(i).IsExists() < 0 Then
                        objMH(i).SLTonKH = ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value)
                        objMH(i).Insert()
                    Else
                        objMH(i).UpdateNgayTaoTon(dtNgay.Value.Date)
                        'Cap nhat lai so luong ton cua mat hang
                        objMH(i).AddSLTON(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value), ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slth").Value))
                    End If

                    'Du mat hang la them moi hay da co roi thi van lay lai mathang_id va code de them SLNX
                    Dim objSLNX As CSLNX
                    Dim dr As DataGridViewRow = gridCTPhieu.Rows(i)
                    objSLNX = New CSLNX()
                    objSLNX.DPNX_ID = objPhieuNhap.DPNX_ID
                    objSLNX.MATHANG_ID = objMH(i).MatHang_ID
                    objSLNX.SLKH = ChuanHoaSo(dr.Cells("slkh").Value)
                    objSLNX.SLTH = ChuanHoaSo(dr.Cells("slth").Value)
                    objSLNX.THANHTIEN = ChuanHoaSo(dr.Cells("thanhtien").Value)
                    Try
                        objSLNX.GhiChu = dr.Cells("ghichu").Value
                    Catch ex As Exception
                        objSLNX.GhiChu = Nothing
                    End Try
                    objSLNX.Insert()
                Next

                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.ThemMoi, objPhieuNhap)
            End If
            ShowMessages("Đã thêm phiếu mới xong.")
            Return True
        End If
        Return False
    End Function

    Public Function UpdatePhieuNXNoiBo() As Boolean
        Dim objMH(RowCount - 1) As CMatHang
        If PopulatePhieuXuatInfo() Then
            'Lay thong tin mat hang PHIEU XUAT NB
            For i As Integer = 0 To RowCount - 1
                If gridCTPhieu.Rows(i).Cells("makho").Value = "" Or gridCTPhieu.Rows(i).Cells("makho").Value = "0001" Then
                    ShowError("Kho đi chưa chọn")
                    gridCTPhieu.Rows(i).Cells("makho").Selected = True
                    Return False
                End If

                If gridCTPhieu.Rows(i).Cells("makhoden").Value = "" Or gridCTPhieu.Rows(i).Cells("makhoden").Value = "0001" Then
                    ShowError("Kho đến chưa chọn")
                    gridCTPhieu.Rows(i).Cells("makhoden").Selected = True
                    Return False
                End If
                objMH(i) = CMatHangs.GetMatHangByMa(gridCTPhieu.Rows(i).Cells("mathang_id").Value)
            Next

            'Kiem tra lai xem so luong luc bat dau ghi co > slton nua ko (truong hop dung nhieu may khi xuat phieu)
            Dim objMHang As CMatHang
            Dim drMH As DataGridViewRow
            Dim strErr As String
            For i As Integer = 0 To RowCount - 1
                drMH = gridCTPhieu.Rows(i)
                objMHang = CMatHangs.GetMatHangByMa(drMH.Cells("mathang_id").Value)
                CMatHangs.GetSLTonDenNgay(objPhieuXuat.DPNX_ID, objMHang.MatHang_ID, dtNgay.Value.Date, sltonkh, Nothing, Nothing, Nothing)
                If drMH.Cells("slkh").Value > sltonkh Then
                    strErr = "Số lượng kế hoạch của mặt hàng " + drMH.Cells("ten").Value.ToString() + " lớn hơn số lượng tồn kế hoạch"
                    drMH.Selected = True
                    Return False
                End If
            Next

            'Kiem tra va Them phieu nhap neu dc
            If objPhieuXuat.Update() > 0 Then
                'Update lai slton cua cac mathang <=> xoa het du lieu trong bang SLNX
                CMatHangs.ResetSLTONMatHangByDPNX(objPhieuXuat.DPNX_ID)
                'Xoa het cac SLNX trong tblSLNX theo DPNX_ID
                CSLNXs.DeleteSLNXByDPNX_ID(objPhieuXuat.DPNX_ID)

                Dim i As Integer = 0
                For i = 0 To RowCount - 1
                    objMH(i).MatHang_ID = gridCTPhieu.Rows(i).Cells("mathang_id").Value
                    objMH(i).SubstractSLTON(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value), ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slth").Value))
                Next

                'Them lai cac SLNX vao tblSLNX
                Dim objSLNX As CSLNX
                For i = 0 To RowCount - 1
                    Dim dr As DataGridViewRow = gridCTPhieu.Rows(i)
                    objSLNX = New CSLNX()
                    objSLNX.DPNX_ID = objPhieuXuat.DPNX_ID
                    objSLNX.MATHANG_ID = dr.Cells("mathang_id").Value
                    objSLNX.SLKH = ChuanHoaSo(dr.Cells("slkh").Value)
                    objSLNX.SLTH = ChuanHoaSo(dr.Cells("slth").Value)
                    objSLNX.THANHTIEN = ChuanHoaSo(dr.Cells("thanhtien").Value)
                    Try
                        objSLNX.GhiChu = dr.Cells("ghichu").Value
                    Catch ex As Exception
                        objSLNX.GhiChu = Nothing
                    End Try
                    objSLNX.Insert()
                Next

                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.Sua, objPhieuXuat)
            End If


            '***********************************************'
            ''    CHUYEN DOI THONG TIN THANH PHIEU NHAP    ''
            '***********************************************'
            'Thong tin Dau Phieu Nhap
            objPhieuNhap = New CPhieuNX(objPhieuXuat)
            objPhieuNhap.DPNX_ID = CPhieuNXs.GetPhieuBySoPhieu(enumDOITUONG.TINHCHATNHAP, txtSoPhieu.Text).DPNX_ID
            objPhieuNhap.NX = LocNhapXuat(enumDOITUONG.TINHCHATNHAP)
            If lblTCN_ID.Text = "" Then
                objPhieuNhap.TCNX = Nothing
            Else
                objPhieuNhap.TCNX = lblTCN_ID.Text
            End If
            objPhieuNhap.LK = lblLKN_ID.Text

            If objPhieuNhap.Update() > 0 Then
                'Update lai slton cua cac mathang <=> xoa het du lieu trong bang SLNX
                CMatHangs.ResetSLTONMatHangByDPNX(objPhieuNhap.DPNX_ID)
                'Xoa het cac SLNX trong tblSLNX theo DPNX_ID
                CSLNXs.DeleteSLNXByDPNX_ID(objPhieuNhap.DPNX_ID)

                'Cap nhat lai nhung thay doi cua grid vao tblSLNX va tblTON
                For i As Integer = 0 To RowCount - 1
                    'Them cac mat hang moi vao
                    If objMH(i).Lo = "" Then
                        objMH(i).Lo = Nothing
                    End If
                    If objMH(i).HanSD = "" Then
                        objMH(i).HanSD = Nothing
                    End If
                    objMH(i).LK = CType(cmbLKN.SelectedItem, CDoiTuong).KH
                    objMH(i).Kho = gridCTPhieu.Rows(i).Cells("makhoden").Value
                    'Kiem tra mat hang nay da ton tai chua
                    If objMH(i).IsExists() < 0 Then
                        objMH(i).SLTonKH = ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value)
                        objMH(i).Insert()
                    Else
                        'Cap nhat lai so luong ton va ngay tao ton (neu can) cua mat hang
                        objMH(i).UpdateNgayTaoTon(dtNgay.Value.Date)
                        objMH(i).AddSLTON(ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slkh").Value), ChuanHoaSo(gridCTPhieu.Rows(i).Cells("slth").Value))
                    End If

                    'Du mat hang la them moi hay da co roi thi van lay lai mathang_id va code de them SLNX
                    Dim objSLNX As CSLNX
                    Dim dr As DataGridViewRow = gridCTPhieu.Rows(i)
                    objSLNX = New CSLNX()
                    objSLNX.DPNX_ID = objPhieuNhap.DPNX_ID
                    objSLNX.MATHANG_ID = objMH(i).MatHang_ID
                    objSLNX.SLKH = ChuanHoaSo(dr.Cells("slkh").Value)
                    objSLNX.SLTH = ChuanHoaSo(dr.Cells("slth").Value)
                    objSLNX.THANHTIEN = ChuanHoaSo(dr.Cells("thanhtien").Value)
                    Try
                        objSLNX.GhiChu = dr.Cells("ghichu").Value
                    Catch ex As Exception
                        objSLNX.GhiChu = Nothing
                    End Try
                    objSLNX.Insert()
                Next

                '==========================
                'Write log
                CLogs.WriteLog_PhieuNX(enumAction.Sua, objPhieuNhap)
            End If
            ShowMessages("Đã cập nhật xong.")
            Return True
        End If
        Return False
    End Function

    Private Sub btnCapNhat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhat.Click, btnCapnhatNew.Click
        Try
            '****************************************
            '       KIEM TRA RANG BUOC              '
            '****************************************
            If cmbLoaiMH.SelectedIndex < 0 Then
                ShowMessages("Chưa chọn Loại mặt hàng")
                If cmbLoaiMH.CanFocus Then
                    cmbLoaiMH.Focus()
                End If
                Exit Sub
            End If

            If txtSoPhieu.Text = "" Then
                ShowMessages("Số Phiếu chưa nhập")
                If txtSoPhieu.CanFocus Then
                    txtSoPhieu.Focus()
                End If
                Exit Sub
            End If

            If lblDVGN_ID.Text = "" Then
                ShowMessages("Đơn vị giao nhận chưa chọn")
                If txtDVGN.CanFocus Then
                    txtDVGN.Focus()
                End If
                Exit Sub
            End If

            If lblTCN_ID.Text = "" Then
                ShowMessages("Tính chất nhập chưa chọn")
                If txtTCN.CanFocus Then
                    txtTCN.Focus()
                End If
                Exit Sub
            End If

            If RowCount = 0 Then
                ShowMessages("Chưa nhập các mặt hàng.")
                Exit Sub
            End If

            'Kiem tra xem mat hang da co so luong ke hoach chua?
            For i As Integer = 0 To RowCount - 1
                If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                    Try
                        Dim SLTonKH As Double
                        SLTonKH = gridCTPhieu.Rows(i).Cells("slkh").Value
                        If SLTonKH = 0 Then
                            ShowError("Số lượng kế hoạch chưa nhập.")
                            gridCTPhieu.Rows(i).Cells("slkh").Selected = True
                            Exit Sub
                        End If
                    Catch ex As Exception
                        ShowError("Số lượng kế hoạch chưa nhập.")
                        gridCTPhieu.Rows(i).Cells("slkh").Selected = True
                        Exit Sub
                    End Try
                End If
            Next

            'Kiem tra xem cac Kho Den da co chua
            For i As Integer = 0 To RowCount - 1
                If gridCTPhieu.Rows(i).Cells("makhoden").Value Is DBNull.Value Then
                    ShowError("Kho đến chưa chọn.")
                    gridCTPhieu.Rows(i).Cells("makhoden").Selected = True
                    Exit Sub
                End If
            Next

            'Kiem tra xem hai Mặt hàng giống nhau có cùng Kho Đến hay không?
            For i As Integer = 0 To RowCount - 2
                For j As Integer = i + 1 To RowCount - 1
                    If gridCTPhieu.Rows(i).Cells("mathang_id").Value = gridCTPhieu.Rows(j).Cells("mathang_id").Value _
                    And gridCTPhieu.Rows(i).Cells("makho").Value = gridCTPhieu.Rows(j).Cells("makho").Value _
                    And gridCTPhieu.Rows(i).Cells("makhoden").Value = gridCTPhieu.Rows(j).Cells("makhoden").Value Then
                        Dim str As String = String.Format("Hai Mặt hàng ở dòng {0} và {1} giống nhau không được chuyển đến cùng một Kho.", i + 1, j + 1)
                        ShowMessages(str)
                        Exit Sub
                    End If
                Next
            Next

            'Kiem tra xem tổng số lượng của một Mặt hàng chuyển đi có > sl tồn của mặt hàng đó ko?
            Dim iSLCHUYENDI As Double = 0
            For i As Integer = 0 To RowCount - 1
                'Tính sltonkh của mặt hàng theo thời điểm cụ thể
                If dtNgay.Value.Date >= Date.Today Then
                    If objPhieuXuat Is Nothing Then
                        sltonkh = gridCTPhieu.Rows(i).Cells("sltonkh").Value
                    Else
                        CMatHangs.GetSLTonDenNgay(objPhieuXuat.DPNX_ID, gridCTPhieu.Rows(i).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                    End If
                Else
                    If objPhieuXuat Is Nothing Then
                        CMatHangs.GetSLTonDenNgay(-1, gridCTPhieu.Rows(i).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                    Else
                        CMatHangs.GetSLTonDenNgay(objPhieuXuat.DPNX_ID, gridCTPhieu.Rows(i).Cells("mathang_id").Value, dtNgay.Value, sltonkh, sltonth, Nothing, Nothing)
                    End If
                End If
                'Tính tổng số lượng chuyển đi của mặt hàng
                iSLCHUYENDI = 0
                For j As Integer = i To RowCount - 1
                    If gridCTPhieu.Rows(i).Cells("mathang_id").Value = gridCTPhieu.Rows(j).Cells("mathang_id").Value Then
                        iSLCHUYENDI += gridCTPhieu.Rows(j).Cells("SLKH").Value
                    End If
                Next

                If iSLCHUYENDI > sltonkh Then
                    Dim str As String
                    str = String.Format("Tổng Số lượng chuyển đi của mặt hàng {0}-{1} là {2} lớn hơn số lượng tồn {3}.", gridCTPhieu.Rows(i).Cells("ma").Value, gridCTPhieu.Rows(i).Cells("code").Value, iSLCHUYENDI.ToString(FormatQuantityStyle()), sltonkh.ToString(FormatQuantityStyle()))
                    gridCTPhieu.Rows(i).Selected = True
                    ShowMessages(str)
                    Exit Sub
                End If
            Next

            '****************************************
            '       BẮT ĐẦU THỰC HIỆN THÊM          '
            '****************************************
            If objPhieuXuat Is Nothing Then
                If Not InsertPhieuNXNoiBo() Then
                    objPhieuXuat = Nothing
                    objPhieuNhap = Nothing
                    Exit Sub
                End If
            Else
                If Not UpdatePhieuNXNoiBo() Then
                    objPhieuXuat = Nothing
                    objPhieuNhap = Nothing
                    Exit Sub
                End If
            End If

            'Neu la cap nhat va close
            If sender Is btnCapNhat Then
                If fViewPhieuNX IsNot Nothing Then
                    fViewPhieuNX.RefreshForm()
                End If
            Else 'Neu la cap nhat va create new
                objPhieuXuat = Nothing
                objPhieuNhap = Nothing
                Init()
            End If
        Catch ex As Exception
            ShowMessages(ex.ToString())
        End Try
    End Sub

    Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Me.Close()
    End Sub

    Private Sub btnThemMH_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If cmbLKX.SelectedIndex = cmbLKN.SelectedIndex Then
            If MessageBox.Show("Loại Kho chuyển đến phải khác với Loại Kho chuyển đi.", "Thông báo") Then
                If cmbLKN.CanFocus() Then
                    cmbLKN.Focus()
                End If
                Exit Sub
            End If
        End If
        Dim objDT As CDoiTuong = CType(cmbLKX.SelectedItem, CDoiTuong)
        Dim frm As New frmQuanLyLoHang(objDT.KH, CType(cmbLoaiMH.SelectedItem, CLoaiThuoc).MaLoaiThuoc)
        frm.fCallPhieuNX = Me
        frm.ShowDialog(Me)
    End Sub
#End Region

#End Region

#Region "Functions"
    ''Ham nay dung de hien thi huong dan cho nguoi su dung
    'Public Function GetLabelNotify(Optional ByVal eNotify As enumLabelNotify = enumLabelNotify.None) As String
    '    Dim str As String = ""
    '    Select Case eNotify
    '        Case enumLabelNotify.DOITUONG
    '            str = "Nhấn F1 hoặc đúp chuột để chọn"
    '        Case enumLabelNotify.SLColumn
    '            str = "Bạn không có quyền sửa cột này"
    '    End Select
    '    Return str
    'End Function

    Public Sub Init()
        If objPhieuXuat IsNot Nothing Then
            With objPhieuXuat
                txtSoPhieu.Text = .SOPHIEU
                cmbLoaiMH.SelectedValue = .LOAIMH
                dtNgay.Value = .NGAY
                txtDVGN.Text = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.DONVI, .DVGN).Ten
                lblDVGN_ID.Text = .DVGN
                txtNguoiVP.Text = .NGUOIVP
                lblLKX_ID.Text = .LK
                cmbLKX.SelectedValue = .LK
                txtTheoLenh.Text = .THEOLENH
                txtSoKH.Text = .SOKH
                txtSoKien.Text = .SOKIEN
                txtTrLuong.Text = .TRLUONG
                txtTGiaTri.Text = .TGIATRI.ToString(FormatMoneyStyle())

                If .BCTH = enumBCTH.KH Then
                    lblBCTH.Text = "Chưa xác nhận (KH)"
                ElseIf .BCTH = enumBCTH.TC Then
                    lblBCTH.Text = "Đã xác nhận (TC)"
                    chkTCXacNhan.Checked = True
                End If
            End With

            With objPhieuNhap
                lblLKN_ID.Text = .LK
                cmbLKN.SelectedValue = .LK
            End With
        Else
            txtDVGN.Text = ""
            lblDVGN_ID.Text = ""
            dtNgay.Value = Date.Now
            txtSoPhieu.Text = ""
            txtNguoiVP.Text = g_User.FullName
        End If
        FormatGridStyleCTPhieuNhap()
        ControlSetFocus(cmbLoaiMH)
    End Sub

    'Ham nay dung de hien thi danh muc DVGN va TCNX de chon gia tri
    Public Sub ShowFormDoiTuong(ByVal loai As enumDOITUONG, ByVal value As String)
        Dim frm As New frmDMDoiTuong
        frm.Text = "Chọn đơn vị"
        frm.bCallForm = True
        frm.eDoiTuong = loai
        frm.sFind = value
        frm.ShowDialog()
        If frm.selectedDT IsNot Nothing Then
            lblDVGN_ID.Text = frm.selectedDT.KH
            txtDVGN.Text = frm.selectedDT.Ten
        Else
            lblDVGN_ID.Text = ""
            txtDVGN.Text = ""
        End If
    End Sub

    'Ham nay dung de hien thi danh muc DVGN va TCNX de chon gia tri
    'Public Sub ShowFormDoiTuong(ByRef objCtl As Object, ByVal loai As enumDOITUONG)
    '    Dim frm As New frmDMDoiTuong
    '    Select Case loai
    '        Case enumDOITUONG.DONVI
    '            frm.Text = "Chọn đơn vị"
    '        Case enumDOITUONG.TINHCHATNHAP
    '            frm.Text = "Chọn Tính chất nhập"
    '        Case enumDOITUONG.TINHCHATXUAT
    '            frm.Text = "Chọn Tính chất xuất"
    '    End Select
    '    frm.bCallForm = True
    '    frm.eDoiTuong = loai
    '    frm.sFind = objCtl.Text
    '    frm.ShowDialog()
    '    If frm.selectedDT IsNot Nothing Then
    '        Select Case objCtl.Name
    '            Case txtDVGN.Name
    '                lblDVGN_ID.Text = frm.selectedDT.KH
    '                txtDVGN.Text = frm.selectedDT.Ten
    '            Case txtTCX.Name
    '                lblTCX_ID.Text = frm.selectedDT.KH
    '                txtTCX.Text = frm.selectedDT.Ten
    '            Case txtTCN.Name
    '                lblTCN_ID.Text = frm.selectedDT.KH
    '                txtTCN.Text = frm.selectedDT.Ten
    '        End Select
    '    Else
    '        Select Case objCtl.Name
    '            Case txtDVGN.Name
    '                lblDVGN_ID.Text = ""
    '                txtDVGN.Text = ""
    '            Case txtTCX.Name
    '                lblTCX_ID.Text = ""
    '                txtTCX.Text = ""
    '            Case txtTCN.Name
    '                lblTCN_ID.Text = ""
    '                txtTCN.Text = ""
    '        End Select
    '    End If
    'End Sub

    Public Function PopulatePhieuXuatInfo() As Boolean
        Dim str(2) As String
        Dim len As Integer = 0
        With objPhieuXuat
            .LOAIMH = CType(cmbLoaiMH.SelectedItem, CLoaiThuoc).MaLoaiThuoc
            .SOPHIEU = txtSoPhieu.Text
            .NX = LocNhapXuat(enumDOITUONG.TINHCHATXUAT)
            .DVGN = lblDVGN_ID.Text
            If lblTCX_ID.Text = "" Then
                .TCNX = Nothing
            Else
                .TCNX = lblTCX_ID.Text
            End If
            .LK = lblLKX_ID.Text
            .NGAYPH = DateNull()

            .THEOLENH = txtTheoLenh.Text
            'Kiểm tra độ dài theo lệnh hợp lệ
            len = .ColumnLength("theolenh")
            If len < .THEOLENH.Length Then
                ShowMessages("Chiều dài ký tự của Theo lệnh vượt quá " + len.ToString())
                txtTheoLenh.Focus()
                Return False
            End If

            .HOPDONG = Nothing
            .NGUOIGN = Nothing
            .GGT = Nothing
            .NGAYKGGT = DateNull()
            .NGAYGN = DateNull()

            .NGUOIVP = txtNguoiVP.Text
            len = .ColumnLength("nguoivp")
            If len < .NGUOIVP.Length Then
                ShowMessages("Chiều dài ký tự của Người VP vượt quá " + len.ToString())
                txtNguoiVP.Focus()
                Return False
            End If

            .NGAY = Me.dtNgay.Value.Date()
            Try
                .SOKH = GetRowCount()
            Catch ex As Exception
                .SOKH = 0
            End Try

            Try
                .SOKIEN = CUInt(txtSoKien.Text)
            Catch ex As Exception
                .SOKIEN = Nothing
            End Try

            Try
                .TRLUONG = Single.Parse(txtTrLuong.Text)
            Catch ex As Exception
                .TRLUONG = Nothing
            End Try

            .HTTT = Nothing

            Try
                .TGIATRI = CUInt(txtTGiaTri.Text)
            Catch ex As Exception
                .TGIATRI = 0
            End Try

            If chkTCXacNhan.Checked Then
                .BCTH = 2
            Else
                .BCTH = 1
            End If
            .KYQT = 1
        End With
        Return True
    End Function

    Public Sub FormatGridStyleCTPhieuNhap()
        sdaSLNX = Nothing
        dsDataSet = Nothing
        Try
            sdaSLNX = g_objConnFactory.CreateAdapter
            CSLNXs.CreateDataSetSLNX(sdaSLNX, dsDataSet, objPhieuXuat.DPNX_ID)
        Catch ex As Exception
            CSLNXs.CreateDataSetSLNX(sdaSLNX, dsDataSet, Nothing)
        End Try
        dsDataSet.Tables(0).Columns.Add("makhoden", System.Type.GetType("System.String"))
        dsDataSet.Tables(0).Columns("makhoden").SetOrdinal(dsDataSet.Tables(0).Columns("kho").Ordinal + 1)
        dsDataSet.Tables(0).Columns.Add("khoden", System.Type.GetType("System.String"))
        dsDataSet.Tables(0).Columns("khoden").SetOrdinal(dsDataSet.Tables(0).Columns("makhoden").Ordinal + 1)
        Dim dv As DataView
        dv = dsDataSet.Tables(0).DefaultView
        gridCTPhieu.DataSource = dv

        With gridCTPhieu
            'Frozen
            'Column Combobox makho da set Frozen = True trong luc tao
            .Columns.Item("kho").Frozen = True
            .Columns.Item("ten").Frozen = True
            .Columns.Item("lo").Frozen = True

            .Columns.Item("ma").HeaderText = "Mã"
            .Columns.Item("code").HeaderText = "Code"
            .Columns.Item("kho").HeaderText = "Kho đi"
            .Columns.Item("khoden").HeaderText = "Kho đến"
            .Columns.Item("ten").HeaderText = "Tên hàng"
            .Columns.Item("dvt").HeaderText = "Đvt"
            .Columns.Item("lo").HeaderText = "Lô hàng"
            .Columns.Item("hansd").HeaderText = "Hạn SD"
            .Columns.Item("h").HeaderText = "CCL"
            .Columns.Item("ghichu").HeaderText = "Ghi chú"
            With .Columns.Item("slkh")
                .HeaderText = "SL Kế hoạch"
                .DefaultCellStyle.Format = FormatQuantityStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .DefaultCellStyle.BackColor = Color.LightGreen
            End With
            With .Columns.Item("slth")
                .HeaderText = "SL Thực hiện"
                .DefaultCellStyle.Format = FormatQuantityStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .DefaultCellStyle.BackColor = Color.LightGreen
            End With
            With .Columns.Item("gle")
                .HeaderText = "Đơn giá"
                .DefaultCellStyle.Format = FormatMoneyStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With
            With .Columns.Item("thanhtien")
                .HeaderText = "Thành tiền"
                .DefaultCellStyle.Format = FormatMoneyStyle()
                .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            End With

            .Columns.Item("mathang_id").Visible = False
            .Columns.Item("slnx_id").Visible = False
            .Columns.Item("ma").Visible = False
            .Columns.Item("code").Visible = False
            .Columns.Item("lk").Visible = False
            .Columns.Item("dpnx_id").Visible = False
            .Columns.Item("ngtton").Visible = False
            .Columns.Item("slss11").Visible = False
            .Columns.Item("slkk11").Visible = False
            .Columns.Item("sltonkh").Visible = False
            .Columns.Item("sltonth").Visible = False
            .Columns.Item("sltonss").Visible = False

            .Columns.Item("kho").ReadOnly = True
            .Columns.Item("ten").ReadOnly = True
            .Columns.Item("dvt").ReadOnly = True
            .Columns.Item("lo").ReadOnly = True
            .Columns.Item("hansd").ReadOnly = True
            .Columns.Item("h").ReadOnly = True
            .Columns.Item("gle").ReadOnly = True
            .Columns.Item("thanhtien").ReadOnly = True
            'Kiem tra phan quyen va chi cho nhap column phu hop
            If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                .Columns.Item("makhoden").Visible = True
                .Columns.Item("khoden").Visible = False
                .Columns.Item("makho").Visible = True
                .Columns.Item("kho").Visible = False
                .Columns.Item("slth").Visible = False
                'Add combobox KHO
                AddComboBoxColumns_KhoDi()
                AddComboBoxColumns_KhoDen()
                'Add combobox Han SD
                AddDateTimePickerColumns_HSD()
                gridCTPhieu.AllowUserToAddRows = True
            ElseIf g_User.Ban_ID = enumPHANQUYEN.TCT Then
                .Columns.Item("makhoden").Visible = False
                .Columns.Item("khoden").Visible = True
                .Columns.Item("makho").Visible = False
                .Columns.Item("kho").Visible = True
                .Columns.Item("slkh").ReadOnly = True
                '.Columns.Item("slth").ReadOnly = True
                gridCTPhieu.AllowUserToAddRows = False
            End If

            RowCount = GetRowCount()

            'Lay Kho Den cua phieu nhap noi bo
            If objPhieuNhap IsNot Nothing Then
                Dim dsSLNXPhieuNhap As DataSet
                Dim sdaSLNXPhieuNhap As IDbDataAdapter
                sdaSLNXPhieuNhap = Nothing
                dsSLNXPhieuNhap = Nothing
                sdaSLNXPhieuNhap = g_objConnFactory.CreateAdapter
                CSLNXs.CreateDataSetSLNX(sdaSLNXPhieuNhap, dsSLNXPhieuNhap, objPhieuNhap.DPNX_ID)
                Dim dt As DataTable = dsSLNXPhieuNhap.Tables(0)
                For i As Integer = 0 To RowCount - 1
                    For j As Integer = 0 To dt.Rows.Count - 1
                        'Kiem tra xem gridCTPhieu( chua mat hang phieu xuat) va dt( chua mat hang phieu nhap) co cung ma,gle,slkh khong neu co thi add kho den
                        If CompareValue(gridCTPhieu.Rows(i).Cells("ma").Value, dt.Rows(j).Item("ma")) And _
                        CompareValue(gridCTPhieu.Rows(i).Cells("ten").Value, dt.Rows(j).Item("ten")) And _
                        CompareValue(gridCTPhieu.Rows(i).Cells("lo").Value, dt.Rows(j).Item("lo")) And _
                        CompareValue(gridCTPhieu.Rows(i).Cells("h").Value, dt.Rows(j).Item("h")) And _
                        CompareValue(gridCTPhieu.Rows(i).Cells("hansd").Value, dt.Rows(j).Item("hansd")) And _
                        CompareValue(gridCTPhieu.Rows(i).Cells("gle").Value, dt.Rows(j).Item("gle")) And _
                        CompareValue(gridCTPhieu.Rows(i).Cells("slkh").Value, dt.Rows(j).Item("slkh")) Then
                            gridCTPhieu.Rows(i).Cells("makhoden").Value = dt.Rows(j).Item("makho")
                            gridCTPhieu.Rows(i).Cells("khoden").Value = dt.Rows(j).Item("kho")
                            Exit For
                        End If
                    Next
                Next
            End If
            For count As Integer = 0 To RowCount - 1
                gridCTPhieu.Rows(count).HeaderCell.Value = (count + 1).ToString
            Next
        End With
    End Sub

    ''Kiem tra xem mat hang can chon da co trong grid chua
    'Private Function isNewMatHang(ByVal mathang_id As Integer) As Boolean
    '    For Each dr As DataGridViewRow In gridCTPhieu.Rows
    '        If dr.Cells("mathang_id").Value IsNot DBNull.Value Then
    '            If CInt(dr.Cells("mathang_id").Value) = mathang_id Then
    '                Return False
    '            End If
    '        End If
    '    Next
    '    Return True
    'End Function

    Public Sub AddMatHang(ByVal objMatHang As CMatHang, ByVal slkh As Double, ByVal count As Integer)
        'If isNewMatHang(objMatHang.MatHang_ID) Then
        'Dim objMatHang As CMatHang = CMatHangs.GetMatHangByMa(mathang_id)
        Dim dt As DataTable = dsDataSet.Tables(0)
        Dim NewRow As DataRow
        NewRow = dt.NewRow
        NewRow("makho") = objMatHang.Kho
        NewRow("kho") = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.KHO, objMatHang.Kho).Ten
        NewRow("mathang_id") = objMatHang.MatHang_ID
        NewRow("ma") = objMatHang.Ma
        NewRow("code") = objMatHang.Code
        NewRow("ten") = objMatHang.Ten
        NewRow("dvt") = objMatHang.DVT
        NewRow("lo") = objMatHang.Lo
        NewRow("hansd") = objMatHang.HanSD
        NewRow("lk") = objMatHang.LK
        NewRow("h") = objMatHang.H
        NewRow("slnx_id") = DBNull.Value
        '***Phai doi ra dung format truoc khi tinh thanh tien
        If slkh > 0 Then
            slkh = CType(slkh.ToString(FormatMoneyStyle()), Double)
        End If
        NewRow("slkh") = slkh
        NewRow("slth") = DBNull.Value
        If objMatHang.Gle > 0 Then
            NewRow("gle") = objMatHang.Gle
            'Tinh thanh tien sau khi format xong
            Dim thanhtien As Double = slkh * objMatHang.Gle
            NewRow("thanhtien") = CType(thanhtien, Long)
        Else
            NewRow("gle") = DBNull.Value
            NewRow("thanhtien") = DBNull.Value
        End If
        NewRow("ghichu") = ""
        Try
            NewRow("dpnx_id") = objPhieuXuat.DPNX_ID
        Catch ex As Exception
            NewRow("dpnx_id") = DBNull.Value
        End Try
        NewRow("sltonkh") = objMatHang.SLTonKH
        NewRow("sltonth") = objMatHang.SLTonTH
        NewRow("sltonss") = objMatHang.SLTonSS
        If count = 1 Then
            Dim RowIndex As Integer = gridCTPhieu.SelectedCells(0).RowIndex
            gridCTPhieu.Rows.RemoveAt(RowIndex) 'Xoa cai dong tai vi tri can insert
            dt.AcceptChanges()
            dt.Rows.InsertAt(NewRow, RowIndex) 'Add vao vi tri insert
            dt.AcceptChanges()
            gridCTPhieu.Rows(RowIndex).HeaderCell.Value = (RowIndex + 1).ToString 'Hien thi lai STT o dau moi dong
            gridCTPhieu.Refresh() 'Refresh lai
        Else
            dt.Rows.InsertAt(NewRow, dt.Rows.Count)
            dt.AcceptChanges()
            gridCTPhieu.Rows(dt.Rows.Count - 1).HeaderCell.Value = (dt.Rows.Count).ToString
            gridCTPhieu.Refresh()
        End If
        'End If
        ShowSoKH_TGiaTri()
    End Sub

    'Ham nay dung de hien thi tong gia tri phieu va so khoan cua phieu
    Public Sub ShowSoKH_TGiaTri()
        RowCount = GetRowCount()
        Dim sum As Double = 0
        For i As Integer = 0 To RowCount - 1
            gridCTPhieu.Rows(i).HeaderCell.Value = (i + 1).ToString
            If gridCTPhieu.Rows(i).Cells("thanhtien").Value IsNot DBNull.Value Then
                sum += gridCTPhieu.Rows(i).Cells("thanhtien").Value
            End If
        Next
        txtSoKH.Text = RowCount.ToString()
        txtTGiaTri.Text = Format(sum, FormatMoneyStyle())
    End Sub

    'Ham nay dung de thay the textbox column thanh combobox column
    Private Sub AddComboBoxColumns_KhoDi()
        Dim comboboxColumn As New DataGridViewComboBoxColumn()
        With comboboxColumn
            .Name = "makho"
            .DataPropertyName = "makho"
            .Frozen = True
            .HeaderText = "Kho đi"
            .FlatStyle = FlatStyle.Flat
            .DropDownWidth = 150 'gridCTPhieu.Columns("kho").Width
            .AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            .Width = gridCTPhieu.Columns("kho").Width
            .DataSource = CDoiTuongs.GetDoiTuongList(enumDOITUONG.KHO)
            .ValueMember = "KH"
            .DisplayMember = "Ten"
        End With
        Try
            Dim index As Integer = gridCTPhieu.Columns("makho").Index
            gridCTPhieu.Columns.Remove("makho")
            gridCTPhieu.Columns.Insert(index, comboboxColumn)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    'Ham nay dung de thay the textbox column thanh combobox column
    Private Sub AddComboBoxColumns_KhoDen()
        Dim comboboxColumn As New DataGridViewComboBoxColumn()
        With comboboxColumn
            .Name = "makhoden"
            .DataPropertyName = "makhoden"
            .Frozen = True
            .HeaderText = "Kho đến"
            .FlatStyle = FlatStyle.Flat
            .DropDownWidth = 150 'gridCTPhieu.Columns("kho").Width
            .AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            .Width = gridCTPhieu.Columns("kho").Width
            .DataSource = CDoiTuongs.GetDoiTuongList(enumDOITUONG.KHO)
            .ValueMember = "KH"
            .DisplayMember = "Ten"
        End With
        Try
            Dim index As Integer = gridCTPhieu.Columns("makhoden").Index
            gridCTPhieu.Columns.Remove("makhoden")
            gridCTPhieu.Columns.Insert(index, comboboxColumn)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub


    'Ham nay dung de thay the text column thanh DateTimePicker Column
    Private Sub AddDateTimePickerColumns_HSD()
        Dim datetimeColumn As New CalendarColumn()
        With datetimeColumn
            .Name = "hansd"
            .DataPropertyName = "hansd"
            .HeaderText = "Hạn SD"
            .Width = 100
        End With
        Try
            Dim index As Integer = gridCTPhieu.Columns("hansd").Index
            gridCTPhieu.Columns.Remove("hansd")
            gridCTPhieu.Columns.Insert(index, datetimeColumn)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    'Ham nay dung de dem so row co trong grid
    Public Function GetRowCount() As UInteger
        Dim mRowCount As UInteger = 0
        Try
            If g_User.Ban_ID = enumPHANQUYEN.KEHOACH Then
                mRowCount = gridCTPhieu.RowCount - 1
            ElseIf g_User.Ban_ID = enumPHANQUYEN.TCT Then
                mRowCount = gridCTPhieu.RowCount
            End If
        Catch ex As Exception
            mRowCount = 0
        End Try
        Return mRowCount
    End Function
#End Region

    Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click
        If objPhieuXuat IsNot Nothing Then
            If MessageBox.Show("Bạn có chắc là xóa 2 phiếu này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                If objPhieuNhap.Delete() > 0 And objPhieuXuat.Delete() > 0 Then
                    ShowMessages("Xong.")
                    If fViewPhieuNX IsNot Nothing Then
                        fViewPhieuNX.RefreshForm()
                    End If
                    Me.Close()
                End If
            End If
        End If
    End Sub

    Private Sub chkTCXacNhan_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkTCXacNhan.CheckedChanged
        If g_User.Ban_ID = enumPHANQUYEN.TCT Then
            If chkTCXacNhan.Checked Then
                For i As Integer = 0 To RowCount - 1
                    gridCTPhieu.Rows(i).Cells("slth").Value = gridCTPhieu.Rows(i).Cells("slkh").Value
                Next
                lblBCTH.Text = "Đã xác nhận (TC)"
            Else
                For i As Integer = 0 To RowCount - 1
                    gridCTPhieu.Rows(i).Cells("slth").Value = DBNull.Value
                Next
                lblBCTH.Text = "Chưa xác nhận (KH)"
            End If
        End If
    End Sub

    Public Function CheckTCXacNhan() As Boolean
        'Hien thi chkTCXacNhan.Checked = true neu tat ca slth > 0
        'Nguoc lai chkTCXacNhan.Checked = false neu ton tai slth <= 0
        Dim isCheckTCXacNhan As Boolean = True
        For Each dr As DataGridViewRow In gridCTPhieu.Rows
            If dr.Cells("slth").Value IsNot DBNull.Value Then
                If dr.Cells("slth").Value <= 0 Then
                    isCheckTCXacNhan = False
                End If
            Else
                isCheckTCXacNhan = False
            End If
        Next
        If isCheckTCXacNhan Then
            lblBCTH.Text = "Đã xác nhận (TC)"
        Else
            lblBCTH.Text = "Chưa xác nhận (KH)"
        End If
        Return isCheckTCXacNhan
    End Function

    Private Sub frmPhieuNXNoiBo_SizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.SizeChanged
        'GroupBoxTTPhieuXuat.Width = PanelTTPhieuNX.Width / 2
    End Sub

    Private Sub frmPhieuNXNoiBo_MaximumSizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.MaximumSizeChanged
        'GroupBoxTTPhieuXuat.Width = PanelTTPhieuNX.Width / 2
    End Sub

    Private Sub PanelTTPhieuNX_SizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PanelTTPhieuNX.SizeChanged
        GroupBoxTTPhieuXuat.Width = PanelTTPhieuNX.Width / 2
    End Sub
End Class